/**
 * Created by wushuai on 16-10-28.
 */
$(document).ready(function() {
    show_items_count();
    show_time();
    show_goods_info();
    clear_data_back_cart_page();
});
function show_goods_info(){
    var goods_items = get_cart_list();
    show_items_list(goods_items);
    show_sum_money(goods_items);
    show_save_money(goods_items);
}
function show_element_to_page(element,value){
    $(element).html(value);
}
function show_items_count(){
    var count=localStorage.getItem("sum_count")||0;
    show_element_to_page("#sum_count",count);
}
function get_cart_list(){
    return  JSON.parse(localStorage.getItem("cart_list"));
}
function show_items_list(goods_items){
    $("#form").tmpl(goods_items).appendTo("#cart_list");
    var save_items=get_save_list(goods_items);
    $("#save_form").tmpl(save_items).appendTo("#save_table");
}
function show_sum_money(goods_items){
    var sum_money=0;
    _.each(goods_items,function(item){
        sum_money+=item.price*item.count;
    });
    sum_money=sum_money.toFixed(2);
    show_element_to_page("#sum_money",sum_money);
}
function show_save_money(goods_items){
    var save_money=0;
    _.each(goods_items, function (item){
        save_money += (item.price) * item.free_count;
    });
    save_money= save_money.toFixed(2);
    show_element_to_page("#save",save_money);
}
function get_save_list(goods_items){
    var save = [];
    _.each(goods_items, function (item){
        if( item.free_count != 0){
            save.push({classification:item.classification, name:item.name, count:item.free_count})
        }
    });
    return save;
}
function get_time(){
    dateDigitToString = function(num){
        return num < 10 ? '0' + num : num;
    };
    var currentDate = new Date(),
        year = dateDigitToString(currentDate.getFullYear()),
        month = dateDigitToString(currentDate.getMonth() + 1),
        date = dateDigitToString(currentDate.getDate()),
        hour = dateDigitToString(currentDate.getHours()),
        minute = dateDigitToString(currentDate.getMinutes()),
        second = dateDigitToString(currentDate.getSeconds()),
        formattedDateString = year + '年' + month + '月' + date + '日 ' + hour + ':' + minute + ':' + second;
    return formattedDateString;
}
function show_time(){
    var time = get_time();
    show_element_to_page(".time",time);
}
function clear_data_back_cart_page() {
    $(".pay").click(function () {
        localStorage.clear();
        window.location.href =  "/untitled1/html/item_list.html"
    });
}
